<?php

namespace app\common\model;

use think\Model;
use app\lib\exception\BaseException;

class Task extends Model
{
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 关闭自动写入update_time字段
    protected $updateTime = false;

    // 关联图片表
    public function images(){
        return $this->belongsToMany('Image','task_image');
    }

    // 关联用户表
    public function user()
    {
        return $this->belongsTo('User');
    }

    // 关联接单表
    public function receiver()
    {
        return $this->hasOne('Receiver');
    }

    // 获取任务详情
    public function getTaskDetail()
    {
        // 获取参数
        $params = request()->param();
        return $this->with(['user'=>function($query){
            return $query->field('id,username,userpic')->with(['userinfo']);
        },'images'=>function($query){
            return $query->field('url');
        }])->find($params['id']);
    }

    // 创建任务
    public function createTask()
    {
        // 获取所有参数
        $params = request()->param();
        $userModel = new User();
        // 获取用户id
        $user_id = request()->userId;
        $currentUser = $userModel->get($user_id);
        $path = $currentUser->userinfo->path;
        $task = $this->create([
            'user_id'=>$user_id,
            'title'=>$params['title'],
            'titlepic'=>'',
            'money'=>$params['money'],
            'descript'=>$params['descript'],
            'address_name'=>$params['address_name'] ? $params['address_name'] : ($path ? $path : '未知'),
            'address_code'=>$params['address_code'] ? $params['address_code'] : '未知',
            'service_type'=>$params['service_type'],
            'task_class_id'=>$params['task_class_id']
        ]);
        if (!$task) TApiException();

        $params['imglist'] = json_decode($params['imglist'],true);
        $imglistLength = count($params['imglist']);
        if($imglistLength > 0){
            $ImageModel = new Image();
            $imgidarr = [];
            for ($i=0; $i < $imglistLength; $i++) {
                // 验证图片是否存在，是否是当前用户上传的
                $imagemodel = $ImageModel->isImageExist($params['imglist'][$i]['id'],$user_id);
                if ($imagemodel){
                    // 设置第一张为封面图
                    if ($i === 0) {
                        $task->titlepic = getFileUrl($imagemodel->url);
                        $task->save();
                    }
                    $imgidarr[] = $params['imglist'][$i]['id'];
                }
            }
            // 发布关联
            if(count($imgidarr)>0) $task->images()->attach($imgidarr,['create_time'=>time()]);
        }
        // 返回成功
        $data = $this->with(['user'=>function($query){
            return $query->field('id,username,userpic')->with(['userinfo']);
        },'images'=>function($query){
            return $query->field('url');
        }])->find($task->id);
        return $data;
    }

    // 取消任务
    public function cancel()
    {
        // 获取所有参数
        $params = request()->param();

        $task = $this->find($params['task_id']);
        $task->status = -1;
        $task->save();
    }

    // 验证当前用户是否为发布者
    public function isCurrentUser()
    {
        $params = request()->param();
        $task = $this->find($params['task_id']);
        return ($task->user_id == request()->userId) ? true : false;
    }

    // 接单
    public function createOrder()
    {
        // 获取参数
        $params = request()->param();
        // 判断是否存在任务订单
        $order = $this->receiver()->where(['task_id' => $params['task_id']])->find();
        if($order) throw new BaseException(['code'=>200,'msg'=>'该订单已被接','errorCode'=>30005]);

        // 创建订单
        $order = $this->receiver()->create([
            'order_no'=>$this->createOrderNo(),
            'user_id'=>$params['userId'],
            'task_id'=>$params['task_id']
        ]);
        if (!$order) TApiException();

        // 修改任务状态
        $task = $this->find($params['task_id']);
        $task->status = 2;
        $task->save();

        $orderArr = $order->toArray();
        $orderArr['taskInfo'] = $task->toArray();
        return $orderArr;
    }

    // 创建订单号
    public function createOrderNo()
    {
        return substr(time(), 0,7) . random_int(100, 999);
    }

    // 完成任务
    public function complete()
    {
        // 获取所有参数
        $params = request()->param();
        $order = $this->receiver()->where(['task_id' => $params['task_id']])->find();
        if ($order['status'] !== 3) throw new BaseException(['code'=>200,'msg'=>'该订单还未完成，先请牛人确认完成后再提交','errorCode'=>30006]);

        $task = $this->find($params['task_id']);
        $task->status = 3;
        $task->save();
    }
}
